<!--
 作者：ex_wangshuai
 日期：2016-11-08
 功能：首页-掌天下-品类竞争分析_品牌销售竞争
 参数：
 事件：
-->
<template>
  <div class="marketingCompetition">
    <div class="loading-box">
      <img src="../../../../static/img/loading.gif" class="loading">
    </div>
    <toolbar :view-title="viewTitle">
      <div class="leftButton" type="button" @click="this.$broadcast('goBack')" slot="left-button">&nbsp;</div>
      <div class="rightButton"
           type="button"
           slot='right-button'>
        <div class="filterButton" @click="showFilter" v-show="!filterOpenState">
          <span class="filterIcon" :page-id="routeKey">&nbsp;</span>
          <span>筛选</span>
        </div>
        <div class="menuButton" @click="showSlideMenu" v-show="!filterOpenState">
          <span class="menuIcon">&nbsp;</span>
          <span>菜单</span>
        </div>
        <span v-show="filterOpenState" @click="doFilter" class="filterOver">完成</span>
      </div>
    </toolbar>
    <div class="filter-message-box clearfix">
      <a class="filter-condition" @click="showFilter('pinlei')" href="javascript:;">{{pinlei}}</a>
      <a class="filter-condition" @click="showFilter('pinpai')" href="javascript:;">{{pinpai}}</a>
      <a class="filter-condition" @click="showFilter('pingtai')" href="javascript:;">{{pingtai}}</a>
      <a v-if="startTime" class="filter-condition" @click="showFilter('shijian')" href="javascript:;">{{startTime | timeFilter}} - {{endTime | timeFilter}}</a>
    </div>
    <div class="marketing-competition">
      <div class="slide" v-for="chart in charts">
        <div class="title-time">
          <p class="title">{{chart.subTitle}}</p>
        </div>
        <div v-if="chart.message" v-if="chart.detail.length">
          <div v-for="item in chart.message" class="important">
            {{item}}
          </div>
        </div>
        <div class="chartContainer chartContainer{{$index}}" v-show="chart.detail.length">
        </div>
        <div class="item-data" v-if="!chart.detail.length">
          暂无数据
        </div>
        <div class="division{{$index}}"></div>
      </div>
    </div>
    <page-turning :mkey="routeKey" :page-id="'industry'">
    </page-turning>
    <slide-list v-if="showList">
    </slide-list>
    <filter-view v-show="filterOpenState"
                 :default-org-id="defaultOrgId"
                 :default-category="defaultCategory"
                 :default-category-id="defaultCategoryId"
                 :choose-platforms= "pingtai"
                 :choose-platforms-id= "pingtaiId"
                 :page-id="routeKey"
                 :filter-button = "filterButton"
                 :default-start-date="startTime"
                 :default-end-date="endTime">
    </filter-view>
    <confirm :show.sync="timeoutStatus"
             title="加载失败,您可以"
             cancel-text="返回首页"
             confirm-text="重新加载"
             @on-cancel="this.$route.router.go('/home')"
             @on-confirm="reload">
    </confirm>
    <confirm :show.sync="show" title="是否退出？" cancel-text="取消" confirm-text="确定" @on-confirm="onAction('确认')"></confirm>
  </div>
</template>

<script>
  // import Echarts from 'echarts/lib/echarts.js'
  import 'echarts/lib/component/legend'
  import 'echarts/lib/component/tooltip'
  import 'echarts/lib/chart/line'
  import 'echarts/lib/chart/pie'
  import Toolbar from '../../common/Toolbar.vue'
  import pageTurning from '../../common/pageTurning.vue'
  import slideList from '../list/slideList.vue'
  import FilterView from '../../common/FilterView.vue'
  import Confirm from 'vux/dist/components/Confirm'

  export default{
    components: {
      Toolbar,
      pageTurning,
      slideList,
      FilterView,
      Confirm
    },
    data () {
      var data = {}
      data.show = false
      data.timeoutStatus = false
      data.pinlei = '所有品类'
      data.pinpai = '所有品牌'
      data.pingtai = '所有平台'
      data.pingtaiId = ''
      data.startTime = ''
      data.endTime = ''
      data.filterButton = ''
      data.size10 = 0.19
      data.size12 = 0.23
      data.size13 = 0.25
      data.size14 = 0.27
      data.xiaoliang1 = '销量'
      data.xiaoliang2 = '销量'
      data.showList = false
      data.defaultOrgId = ''
      data.defaultCategory = ''
      data.defaultCategoryId = ''
      data.routeKey = ''
      data.filterOpenState = false
      data.viewTitle = ''
      // 渲染echarts需要用到的数据
      data.charts = []
      data.myChart = {}
      data.currentOption = ''
      data.pieLegend1 = []
      data.pieSelected1 = {'其他': true}
      data.pieData1 = []
      data.pieLegend2 = []
      data.pieSelected2 = {'其他': true}
      data.pieData2 = []
      data.lineLegend = []
      data.lineXaxis = []
      data.lineSeries = []
      data.lineSelected = []
      data.lineLegend1 = []
      data.lineLegend2 = []
      data.lineXaxis1 = []
      data.lineXaxis2 = []
      data.lineSeries1 = []
      data.lineSeries2 = []
      data.lineSelected1 = {}
      data.lineSelected2 = {}
      data.params = {
        mkey: '',
//        refresh: true,
        org_code: '',
        brand: '',
        brand_id: '',
        category_id: '',
        category: '',
        platform_id: '',
        platform: '',
        dateSeg: '',
        startTime: '',
        endTime: ''
      }
      return data
    },
    methods: {
      reload: function () {
        window.location.reload()
      },
      goBack: function () {
//        window.history.back()
        this.show = true
      },
      onAction: function (value) {
        if (value === '确认') {
          window.cordova.exec(function (success) {
          }, function (error) {
            window.alert('Error: ' + error)
          }, 'MideaCommon', 'exit', [])
        }
      },
      doFilter: function () {
        this.$broadcast('doFilter')
      },
      showFilter: function (value) {
        this.filterButton = value
        this.filterOpenState = true
      },
      showSlideMenu: function () {
        this.showList = !this.showList
        var self = this
        setTimeout(function () {
          self.$broadcast('slideStart')
        }, 0)
      },
      // 线图数据处理
      lineDataFunc: function (z, sales) {  // sales 销量
        var lineDataLength = this.charts[z].detail.length
        var lineData = []
        var lineLegend = []
        var lineXaxis = []
        var lineSeries = []
        var lineSelected = {}
        // 判断有几条线 x
        for (var x = 1; x < lineDataLength; x++) {
          if (this.charts[z].detail[0].date !== this.charts[z].detail[x].date) {
            break
          }
        }
        // legend
        for (var e = 0; e < x; e++) {
          lineLegend.push({'name': this.charts[z].detail[e].brand_, 'icon': 'roundRect'})
          lineData.push([])
          for (var d = e; d < lineDataLength; d = d + x) {
            lineData[e].push(this.charts[z].detail[d][sales])
          }
        }
        // legend默认选中的线
        var legendData = lineLegend
        for (var j = 0; j < x; j++) {
          if (j > 3) {
            lineSelected[legendData[j].name] = false
          }
        }
        // x轴
        for (var f = 0; f < lineDataLength; f = f + x) {
          if (f === 0) {
            lineXaxis.push({value: this.charts[z].detail[f].date, textStyle: {align: 'left'}})
          } else {
            lineXaxis.push({value: this.charts[z].detail[f].date, textStyle: {align: 'right'}})
          }
        }
        for (var g = 0; g < x; g++) {
          lineSeries.push({'name': lineLegend[g].name, 'type': 'line', 'data': lineData[g]})
        }
        this.lineLegend = lineLegend
        this.lineXaxis = lineXaxis
        this.lineSeries = lineSeries
        this.lineSelected = lineSelected
      },
      getHttpData: function (httpUrl, params) {
        this.$http.post(httpUrl, params, {_timeout: 30000}).then((res) => {
          if (res.json().error) {
            this.timeoutStatus = true
            return
          }
          var data = res.json()
          this.defaultOrgId = data.org_code || ''
          this.defaultCategory = data.category || ''
          this.defaultCategoryId = data.category_id || ''
          this.pinlei = data.categoryCnd || data.category
          this.pinpai = data.brandCnd || data.brand
          this.pingtai = data.platformCnd || data.platform
          this.pingtaiId = data.platform_id || ''
          this.startTime = data.startTime || ''
          this.endTime = data.endTime || ''
          document.getElementsByClassName('loading-box')[0].style.display = 'none'
          this.viewTitle = res.json().title
          this.charts = res.json().chartDatas
          var xiaoliang = '销量'
          this.xiaoliang1 = xiaoliang + this.charts[0].saleUnit
          this.xiaoliang2 = xiaoliang + this.charts[2].saleUnit
          this.$broadcast('loadDataDone')
          // 第一个饼图
//          if (this.charts[0].detail.length !== 0) {
          var pieData1 = []
          var pieLegend1 = []
          for (var a = 0; a < this.charts[0].detail.length; a++) {
            pieLegend1.push({'name': this.charts[0].detail[a].brand_show, 'icon': 'roundRect'})
            pieData1.push({'value': this.charts[0].detail[a].sales, 'name': this.charts[0].detail[a].brand_show})
          }
          this.pieLegend1 = pieLegend1
          this.pieData1 = pieData1
//          }
          // 第二个饼图
//          if (this.charts[1].detail.length !== 0) {
          var pieData2 = []
          var pieLegend2 = []
          for (var b = 0; b < this.charts[1].detail.length; b++) {
            pieLegend2.push({'name': this.charts[1].detail[b].brand_show, 'icon': 'roundRect'})
            pieData2.push({'value': this.charts[1].detail[b].sales_amount, 'name': this.charts[1].detail[b].brand_show})
          }
          this.pieLegend2 = pieLegend2
          this.pieData2 = pieData2
//          }
          // 第三个多线图
//          if (this.charts[2].detail.length !== 0) {
          this.lineDataFunc(2, 'sales')
          this.lineLegend1 = this.lineLegend
          this.lineXaxis1 = this.lineXaxis
          this.lineSeries1 = this.lineSeries
          this.lineSelected1 = this.lineSelected
//          }
          // 第四个多线图
//          if (this.charts[3].detail.length !== 0) {
          this.lineDataFunc(3, 'sales_amount')
          this.lineLegend2 = this.lineLegend
          this.lineXaxis2 = this.lineXaxis
          this.lineSeries2 = this.lineSeries
          this.lineSelected2 = this.lineSelected
//          }
          if (res.json().chartDatas.length === 0) {
            document.getElementsByClassName('marketing-competition')[0].style.display = 'none'
            document.getElementsByClassName('no-data')[0].style.display = 'block'
            return
          }
          setTimeout(function () {
            var htmlHeight = document.documentElement.clientHeight
            var toorBarHeight = document.getElementsByClassName('toolbar')[0].clientHeight
            var filterMessageBox = document.getElementsByClassName('filter-message-box')[0].clientHeight
            var tapHeight = document.getElementsByClassName('tab')[0].clientHeight
            var contentDiv = document.getElementsByClassName('marketing-competition')[0]
            contentDiv.style.height = htmlHeight - toorBarHeight - filterMessageBox - tapHeight + 'px'
          }, 0)
        }, (res) => {
          this.timeoutStatus = true
        })
      }
    },
    watch: {
      lineSelected2: function () {
        var self = this
        var pieOption1 = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}<br/>' + self.xiaoliang1 + '：{c}<br/>占有率：{d}%'
          },
          legend: {
            data: this.pieLegend1,
            itemWidth: this.size10,
            itemHeight: this.size10,
            itemGap: this.size14,
            left: '2.5%',
            right: '2.5%',
            textStyle: {
              color: '#999',
              fontSize: this.size13
            },
            selected: this.pieSelected1
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
//              startAngle: 0,
              hoverAnimation: false,
              label: {
                normal: {
                  formatter: '{b}\n{d}%',
                  textStyle: {
                    fontSize: this.size14,
                    color: '#999999'
                  }
                }
              },
              labelLine: {
                normal: {
                  length: 18,
                  length2: 4,
                  lineStyle: {
                    color: '#999999'
                  }
                }
              },
              center: ['50%', '60%'],
//              clockwise: false,
              data: this.pieData1
            },
            {
              type: 'pie',
              radius: '17%',
              hoverAnimation: false,
              center: ['50%', '58%'],
              data: [10],
              itemStyle: {
                normal: {
                  color: 'rgba(255, 255, 255, 0.5)'
                }
              },
              silent: true
            }
          ],
          color: ['#2578DA', '#3385E5', '#4696F4', '#5FA9FF', '#7CB8FC', '#B6D7FD', '#9DC9FB', '#B6D7FD', '#E8F2FF']
        }
        var pieOption2 = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}<br/>销额(万元)：{c}<br/>占有率：{d}%'
          },
          legend: {
            data: this.pieLegend2,
            itemWidth: this.size10,
            itemHeight: this.size10,
            itemGap: this.size14,
            left: '2.5%',
            right: '2.5%',
            textStyle: {
              color: '#999',
              fontSize: this.size13
            },
            selected: this.pieSelected2
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
//              startAngle: 0,
              hoverAnimation: false,
              label: {
                normal: {
                  formatter: '{b}\n{d}%',
                  textStyle: {
                    fontSize: this.size14,
                    color: '#999999'
                  }
                }
              },
              labelLine: {
                normal: {
                  length: 18,
                  length2: 4,
                  lineStyle: {
                    color: '#999999'
                  }
                }
              },
              center: ['50%', '60%'],
              data: this.pieData2
            },
            {
              type: 'pie',
              radius: '17%',
              hoverAnimation: false,
              center: ['50%', '58%'],
              data: [10],
              itemStyle: {
                normal: {
                  color: 'rgba(255, 255, 255, 0.5)'
                }
              },
              silent: true
            }
          ],
          color: ['#7125DA', '#8033E5', '#9246F4', '#A45FFF', '#C29DFB', '#CFB6FD', '#C29DFB', '#CFB6FD', '#E6D3FF']
        }
        var lineOption1 = {
          tooltip: {
            trigger: 'axis',
            formatter: function (obj) {
              var show = obj[0].name
              for (var i = 0; i < obj.length; i++) {
                show += '<br/>' + obj[i].seriesName + ': ' + obj[i].value
              }
              return show
            }
          },
          legend: {
            data: this.lineLegend1,
            itemWidth: this.size10,
            itemHeight: this.size10,
            itemGap: this.size14,
            textStyle: {
              color: '#999',
              fontSize: this.size13
            },
            top: '1%',
            left: '2.5%',
            right: '2.5%',
            selected: this.lineSelected1
          },
          grid: {
            show: true,
            top: '22%',
            left: '10%',
            right: '11%',
            bottom: '6%',
            containLabel: true,
            backgroundColor: '#FAFCFF',
            borderWidth: 0
          },
          xAxis: {
            type: 'category',
            axisLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                color: '#4A90E2'
              }
            },
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              },
              interval: this.lineXaxis1.length - 2
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            data: this.lineXaxis1
          },
          yAxis: {
            type: 'value',
            name: '         ' + this.xiaoliang2,
            nameGap: 4,
            nameTextStyle: {
              color: '#999999',
              fontSize: this.size12
            },
            axisLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                color: '#4A90E2'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              }
            },
            splitLine: {
              show: false
            }
          },
          color: ['#FF8B8B', '#FF8BD1', '#FFD38B', '#B889FF', '#8BB4FF', '#8BB4FF', '#77E1E7', '#67D7FF', '#E4A3FF', '#BCDBFF'],
          series: this.lineSeries1
        }
        var lineOption2 = {
          tooltip: {
            trigger: 'axis',
            formatter: function (obj) {
              var show = obj[0].name
              for (var i = 0; i < obj.length; i++) {
                show += '<br/>' + obj[i].seriesName + ': ' + obj[i].value
              }
              return show
            }
          },
          legend: {
            data: this.lineLegend2,
            itemWidth: this.size10,
            itemHeight: this.size10,
            itemGap: this.size14,
            textStyle: {
              color: '#999',
              fontSize: this.size13
            },
            top: '1%',
            left: '2.5%',
            right: '2.5%',
            selected: this.lineSelected2
          },
          grid: {
            show: true,
            top: '22%',
            left: '10%',
            right: '11%',
            bottom: '6%',
            containLabel: true,
            backgroundColor: '#FAFCFF',
            borderWidth: 0
          },
          xAxis: {
            type: 'category',
            axisLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                color: '#4A90E2'
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              },
              interval: this.lineXaxis2.length - 2
            },
            data: this.lineXaxis2
          },
          yAxis: {
            type: 'value',
            name: '                   销额(万元)',
            nameGap: 5,
            nameTextStyle: {
              color: '#999999',
              fontSize: this.size12
            },
            axisLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                color: '#4A90E2'
              }
            },
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            }
          },
          color: ['#FF8B8B', '#FF8BD1', '#FFD38B', '#B889FF', '#8BB4FF', '#8BB4FF', '#77E1E7', '#67D7FF', '#E4A3FF', '#BCDBFF'],
          series: this.lineSeries2
        }
        this.$nextTick(function () {
          // 返回的数据需要用echarts显示的
          var chartDomLength = document.getElementsByClassName('chartContainer').length
          var chartDomArray = new Array(chartDomLength)
          for (var x = 0; x < chartDomLength; x++) {
            chartDomArray[x] = document.getElementsByClassName('chartContainer')[x]
            this.myChart = window.Echarts.init(chartDomArray[x])
            if (x === 0) {
              this.myChart.setOption(pieOption1)
            } else if (x === 1) {
              this.myChart.setOption(pieOption2)
            } else if (x === 2) {
              this.myChart.setOption(lineOption1)
            } else if (x === 3) {
              this.myChart.setOption(lineOption2)
            }
          }
        })
      }
    },
    events: {
      'filterConditions': function (filterConditions) {
        document.getElementsByClassName('loading-box')[0].style.display = 'block'
        if (filterConditions.brand !== '') {
          this.pinpai = filterConditions.brand
          this.pinpai = this.pinpai.replace(/,/g, '，')
        }
        if (filterConditions.platform !== '') {
          this.pingtai = filterConditions.platform
          this.pingtai = this.pingtai.replace(/,/g, '，')
        }
        this.params.org_code = filterConditions.org_code || ''
        this.params.brand = filterConditions.brand
        this.params.brand_id = filterConditions.brand_id
        this.params.category = filterConditions.category
        this.params.category_id = filterConditions.category_id
        this.params.platform = filterConditions.platform
        this.params.platform_id = filterConditions.platform_id
        this.params.dateSeg = filterConditions.dateSeg
        this.params.startTime = filterConditions.starttime
        this.params.endTime = filterConditions.endtime
        this.params.brand_all = filterConditions.brand_all
        this.params.mkey = this.routeKey
        this.getHttpData(this.httpUrl, this.params)
      }
    },
    created () {
      this.routeKey = 'marketingCompetition'
      this.httpUrl = window.interface.indusPage
      var params = this.params
      params.mkey = this.routeKey
      this.getHttpData(this.httpUrl, params)
      var sizeBase = parseInt(document.documentElement.style.fontSize)
      this.size10 = sizeBase * this.size10
      this.size12 = sizeBase * this.size12
      this.size13 = sizeBase * this.size13
      this.size14 = sizeBase * this.size14
    },
    filters: {
      timeFilter: function (val) {
        if (val) {
          val = val.split('-')
          val = val.join('')
          return val
        }
      }
    },
    ready: function () {
    }
  }
</script>

<style lang="scss" scoped>
  .marketing-competition {
    position: relative;
    /*padding-top: 19vh;*/
    /*margin-bottom: 7.4vh;*/
    height: 80%;
    overflow: auto;
  }
  .filter-message-box{
    width: 100%;
    margin-top: 6.6vh;
    /*position: fixed;*/
    /*top: 6.6vh;*/
    /*left: 0;*/
    background: white;
    z-index: 101;
    font-size: 0.28rem;
    padding: 1.7vh 0 2.1vh .3rem;
    box-sizing: border-box;
    border-bottom: 1px solid rgb(238, 238, 238);
  }

  .filter-condition{
    margin-right: 0.2rem;
    margin-top: 1.1vh;
    font-size: 0.24rem;
    float: left;
    color: #4A90E2;
    padding: 0.35vh 1.2vh;
    box-sizing: border-box;
    border: 1px solid #4A90E2;
    background: #FAFCFF;
    border-radius: 3px;
    max-width: 85%;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }
  .title-time {
    padding: 2.4vh 0 1.3vh 0;
    border-bottom: 1px solid #eeeeee;
    box-sizing: border-box;
  }

  .title {
    font-size: .32rem;
    background: url('../../../../static/img/time-title2.png') no-repeat center right;
    background-position: .3rem center;
    background-size: .28rem .26rem;
    padding-left: .7rem;
    color: #333333;
  }

  .important {
    margin: 1.5vh 0;
    font-size: .28rem;
    padding-left: .3rem;
    color: #666666;
  }

  .division0, .division1, .division2 {
    width: 100%;
    height: 1.5vh;
    background: rgb(238, 238, 238);
  }

  .chartContainer0, .chartContainer1 {
    width: 100%;
    height: 62vh;
  }

  .chartContainer2, .chartContainer3 {
    width: 100%;
    height: 61vh;
  }

  .btnPage {
    position: fixed;
    left: 0;
    top: 50vh;
    width: 100%;
    z-index: 200;
  }

  .btn-previous {
    width: 0.4rem;
    height: 0.8rem;
    float: left;
    background: rgba(0, 0, 0, 0.2);
  }

  .btn-next {
    width: 0.4rem;
    height: 0.8rem;
    float: right;
    background: rgba(0, 0, 0, 0.2);
  }

  .leftButton {
    width: .5rem;
    height: 100%;
    background: url('../../../../static/img/btn-back.png') no-repeat center right;
    background-size: 100%;
  }

</style>
